<?php

//------------------------
// 角色组管理控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\Db;

class AuthGroup extends AdminBase
{
    protected $admin_user_model;
    protected $auth_group_model;
    protected $auth_group_access_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->admin_user_model        = new AdminUserModel();
        $this->auth_group_model        = new AuthGroupModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();
    }

    // 认证规则列表
    public function index(){
        $title = $this->request->param('title','','trim');
        $status   = $this->request->param('status',0,'intval');

        $where = array();
        if ($status) {
            $_status = $status == 2?0:1;
            $where['status'] = array('eq',$_status);
        }
        if ($title) {
             $where['title'] = array('like','%'.$title.'%');
        }

        $info = $this->auth_group_model->where($where)->paginate(10);

        $this->assign('info',$info);
        $this->assign('title',$title);
        $this->assign('status',$status);
        return $this->fetch('index');
    }

    /**
     * @desc 添加/编辑操作
     */
    public function add_proc() {

        $data = $this->request->param();
        $id   = $this->request->param('group_id',0,'intval');

        if ($id) {
            // 编辑
            $data['id'] = $id;
            $validate_result = $this->validate($data, 'AuthGroup.edit');
            if ($validate_result !== true) {
                $this->error($validate_result);
            }
            $res = $this->auth_group_model->allowField(true)->save($data,$id);
            $act = "编辑";
        } else {
            // 添加
            $validate_result = $this->validate($data, 'AuthGroup.add');
            if ($validate_result !== true) {
                $this->error($validate_result);
            }
            $act = "添加";
            $res = $this->auth_group_model->allowField(true)->save($data);
        }

        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' =>  '添加规则' , 'remark' => '添加规则失败' , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->auth_group_model->getError());
        } else {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' => '添加规则' , 'remark' => '分类编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('用户组'.$act.'成功');
        }
    }

    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        $where['isdelete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->auth_group_model->where($where)->delete();

        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '设备管理' , 'action' => '删除滚动广告' , 'remark' => '删除滚动广告失败，广告编号：' . $id , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->auth_group_model->getError());
        } else{
            // 删除成功后，才删除中间表的数据
            $this->auth_group_access_model->where('group_id',$id)->delete();
            // 记录日志
            // $logData = array('module' => '设备管理' , 'action' => '删除滚动广告' , 'remark' => '广告编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('删除成功');
        }
    }

    // 批量删除用户组>>调用
    private function _batch_delete($id){
        $where['isdelete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->auth_group_model->where($where)->delete();

        if ($res == false) {
           return false;
        } else {
            $this->auth_group_access_model->where('group_id',$id)->delete();
            return true;
        }

    }

    // 设置用户组规则
    public function set_auth(){
        $id = $this->request->param('id',0,'intval');

        $rules = $this->auth_group_model->get($id)->rules;

        $rules_array = explode(',',$rules);

        $is_auth = array();
        foreach ($rules_array as $k => $v) {
            $is_auth[$v] = true;
        }

        $model = Db::name('AuthRule');

        $parent = $model->where(array('pid'=>0))->select();

        foreach ($parent as &$data) {
            $child = $model->where(array('pid' => $data['id']))->select();
            $data['child'] = $child;
        }
        unset($data);

        $this->assign('id',$id);
        $this->assign('is_auth',$is_auth);
        $this->assign('parent',$parent);

        return $this->fetch('set_auth_page');

    }

    // 保存用户组规则
    public function save_auth(){
        $info    = $this->request->param('');
        $id      = $info['id'];
        $auths   = isset($info['auth_id'])?$info['auth_id']:array();

        $auths = implode(",", $auths);

        $data = array(
            'id' => $id,
            'rules' => $auths,
        );

        $res = $this->auth_group_model->setAuth($data);

        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error($this->auth_group_model->getError());
        }
    }

    //  设置用户组用户页面
    public function set_user(){
        $id = $this->request->param('id',0,'intval');
        $username = $this->request->param('username','','trim');

        $model = Db::name('AuthGroupAccess');

        $is_user = $model->where('group_id',$id)->field('uid')->select();

        $is_user = twoToOne($is_user,'uid');
        // halt($is_user);

        $where = array();
        $where['status'] = array('EQ',1);

        if ($username) {
             $where['username'] = array('like','%'.$username.'%');
        }

        $info = $this->admin_user_model->where($where)->paginate(10);

        $this->assign('id',$id);
        $this->assign('username',$username);
        $this->assign('is_user',$is_user);
        $this->assign('info',$info);

        return $this->fetch('set_user_page');
    }

    // 保存用户组用户
    public function save_user(){
        $info    = $this->request->param('');
        $id      = $info['id'];
        $users   = isset($info['user_id'])?$info['user_id']:array();


        if ($users) {
            // 先删除$id相关的所有数据
            $this->auth_group_access_model->where('group_id',$id)->delete();
            // 循环添加$users数组中的相关用户到$id 用户组中
            $data = [];
            foreach ($users as $value) {
                $data[] = [
                    'group_id' => $id,
                    'uid'      => $value
                ];
            }
            $res = $this->auth_group_access_model->saveAll($data);
        } else {
            $res = $this->auth_group_access_model->where('group_id',$id)->delete();
        }

        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error($this->auth_group_model->getError());
        }
    }

    // 批量处理
    public function batch_proc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'delete':
                $successData = array();
                $failData = array();
                for ($i=0; $i < count($data['ids']); $i++) { 
                    $result = $this->_batch_delete($data['ids'][$i]);
                    if ($result) {
                        array_push($successData, $data['ids'][$i]);
                    } else {
                        array_push($failData, $data['ids'][$i]);
                    }
                }
                $success = implode(',',$successData);
                $fail   = implode(',',$failData);
                $this->success('删除成功id为：'.$success.'，删除失败id为：'.$fail);
                break;
            case 'disable':
                $res = $this->auth_group_model->where($map)->update(['status' => '0']);
                $act = '禁用';
                break;
            case 'enable':
                $res = $this->auth_group_model->where($map)->update(['status' => '1']);
                $act = '启用';
                break;

            default:
                $this->error('非法操作');
                break;
        }
        if ($res === false) {
            $this->error($this->auth_group_model->getError());
            // 记录日志
        } else {
            $this->success('批量'.$act.'成功');
        }

    }

}